package com.carlos.gateway.controller;


import com.carlos.gateway.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 用来全局处理 Filter 中的异常
 *
 * @author 李健成
 * @date 2021/10/18
 */

public class MyErrorController extends BasicErrorController {

//    @Autowired
    public MyErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties) {
//        super();
        super(errorAttributes, errorProperties);
    }

//    @RequestMapping(value = "/error", produces = {MediaType.APPLICATION_JSON_VALUE})
//    public ResultVO<Void> doHandleError(HttpServletRequest request, HttpServletResponse response) {
//        ServletWebRequest webRequest = new ServletWebRequest(request, response);
//        Map<String, Object> attributes = this.errorAttributes.getErrorAttributes(webRequest, ErrorAttributeOptions.of(ErrorAttributeOptions.Include.STACK_TRACE));
//        Integer status = (Integer) attributes.get("status");
//        String message = (String) attributes.get("message");
//        return new ResultVO<>(String.valueOf(status), message, null);
//    }

//    @Override
//    @RequestMapping("/error")
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        System.out.println("啦啦啦");
        Map<String, Object> attributes = this.getErrorAttributes(request, ErrorAttributeOptions.of(ErrorAttributeOptions.Include.MESSAGE, ErrorAttributeOptions.Include.STACK_TRACE));
//        Integer status = (Integer) attributes.get("status");
        String message = (String) attributes.get("message");
        HttpStatus status = this.getStatus(request);
        ResultVO<Void> result = new ResultVO<>(String.valueOf(status), message, null);
        return new ResponseEntity<Map<String, Object>>(BeanMap.create(result), HttpStatus.OK);
    }

}
